package com.quxiu.system.schedule;

import com.quxiu.common.core.constant.CacheConstants;
import com.quxiu.common.redis.service.RedisService;
import com.quxiu.system.service.ISysAppService;
import com.quxiu.system.service.ISysDataPushRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


@Configuration
@EnableScheduling
@Slf4j
public class ScheduleTask {
    @Resource
    private RedisService redisService;
    @Resource
    private ISysAppService sysAppService;
    @Resource
    private ISysDataPushRecordService sysDataPushRecordService;

    /**
     * 执行数据推送
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void executePushData() {

        String lockKey = CacheConstants.TASK_CACHE_KEY_PREFIX + "executePushData";

        try {
            boolean isLock = redisService.setCacheObjectIfAbsent(lockKey, "lock", 60L * 10, TimeUnit.SECONDS);
            if (isLock) {
                sysAppService.executePushData();
            } else {
                long residueTime = redisService.getExpire(lockKey);
                if (residueTime < 60L * 3) {
                    redisService.expire(lockKey, 60L * 5, TimeUnit.SECONDS);
                }
            }
        } catch (Exception e) {
            log.error("执行数据推送定时任务 error:", e);
        } finally {
            redisService.deleteObject(lockKey);
        }
    }


    /**
     * 删除历史推送数据
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void deleteHistoryPushData() {

        String lockKey = CacheConstants.TASK_CACHE_KEY_PREFIX + "deleteHistoryPushData";

        try {
            boolean isLock = redisService.setCacheObjectIfAbsent(lockKey, "lock", 60L * 10, TimeUnit.SECONDS);
            if (isLock) {
                sysDataPushRecordService.deleteHistoryPushData();
            }
        } catch (Exception e) {
            log.error("删除历史推送数据定时任务 error:", e);
        } finally {
            redisService.deleteObject(lockKey);
        }
    }
}
